<template>
    <a-spin :spinning="loading" tip="加载中...">
      <div class="image-wall-container">
      <button 
        class="scroll-button left-button" 
        @click="scrollLeft" 
        :disabled="scrollPosition <= 0"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 19L8 12L15 5" stroke="#505662" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
      
      <div class="image-wall-wrapper" ref="scrollContainer">
        <div class="image-wall">
          <div v-for="(image, index) in images" :key="index" class="image-item">
            <img
              :src="typeof image === 'string' ? image : image.src" 
              :alt="typeof image === 'string' ? '图片' : (image.alt || '图片')" 
              @load="handleImageLoad(index)"
              @error="handleImageLoad(index)"
            />
          </div>
        </div>
      </div>
      
      <button 
        class="scroll-button right-button" 
        @click="scrollRight"
        :disabled="scrollPosition >= maxScroll"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M9 5L16 12L9 19" stroke="#505662" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
    </div>
    </a-spin>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue';
  
  // 图片数据，可以通过props传入
  const props = defineProps({
    images: {
      type: Array,
      default: () => [
      ]
    },
    scrollStep: {
      type: Number,
      default: 300 // 每次滚动的像素数
    }
  });
  const loading = ref(false);
  const scrollContainer = ref(null);
  const scrollPosition = ref(0);
  const maxScroll = ref(0);
  const loadedImages = ref(0);
  
  // 处理单个图片加载完成
  const handleImageLoad = (index) => {
    loadedImages.value++;
    console.log(`[ImageWall] 图片 ${index} 加载完成，已加载 ${loadedImages.value}/${props.images.length} 张`);
    
    // 当所有图片都加载完成时，重新计算滚动区域
    if (loadedImages.value >= props.images.length) {
      console.log('[ImageWall] 所有图片通过事件监听加载完成');
      // 强制触发布局重新计算
      if (scrollContainer.value) {
        scrollContainer.value.offsetWidth;
        updateMaxScroll();
        console.log(`[ImageWall] 事件监听后计算的最大滚动距离: ${maxScroll.value}`);
        
        // 如果maxScroll仍然为0但实际上有多个图片，可能是计算错误，强制设置为正值
        if (maxScroll.value <= 0 && props.images.length > 1) {
          console.log(`[ImageWall] 通过事件监听检测到${props.images.length}张图片但maxScroll为0，强制启用右侧按钮`);
          maxScroll.value = 1; // 强制设置为正值以启用右侧按钮
        }
      }
    }
  };
  
  // 计算最大滚动距离
  const updateMaxScroll = () => {
    if (scrollContainer.value) {
      maxScroll.value = scrollContainer.value.scrollWidth - scrollContainer.value.clientWidth;
    }
  };
  
  // 向左滚动
  const scrollLeft = () => {
    if (scrollContainer.value) {
      const newPosition = Math.max(0, scrollContainer.value.scrollLeft - props.scrollStep);
      scrollContainer.value.scrollTo({
        left: newPosition,
        behavior: 'smooth'
      });
    }
  };
  
  // 向右滚动
  const scrollRight = () => {
        if (scrollContainer.value) {
      const newPosition = Math.min(maxScroll.value, scrollContainer.value.scrollLeft + props.scrollStep);
      scrollContainer.value.scrollTo({
        left: newPosition,
        behavior: 'smooth'
      });
    }
  };
  
  // 监听滚动事件
  const handleScroll = () => {
    if (scrollContainer.value) {
      scrollPosition.value = scrollContainer.value.scrollLeft;
      updateMaxScroll(); // 更新最大滚动距离
    }
  };
  
  // 等待所有图片加载完成后更新滚动距离
  const updateScrollAfterImagesLoad = async () => {
    loading.value = true;
    // 确保DOM已经渲染
    await new Promise(resolve => setTimeout(resolve, 0));
    
    const images = scrollContainer.value?.querySelectorAll('img') || [];
    console.log(`[ImageWall] 找到 ${images.length} 张图片等待加载`);
    
    const imageLoadPromises = Array.from(images).map(img => {
      if (img.complete) return Promise.resolve();
      return new Promise(resolve => {
        img.onload = resolve;
        img.onerror = resolve; // 即使图片加载失败也继续处理
      });
    });
    
    await Promise.all(imageLoadPromises);
    console.log('[ImageWall] 所有图片加载完成');
    
    // 等待DOM更新，增加等待时间确保布局完成
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 强制触发布局重新计算
    if (scrollContainer.value) {
      // 触发强制回流以确保尺寸计算准确
      scrollContainer.value.offsetWidth;
    }
    
    updateMaxScroll();
    console.log(`[ImageWall] 初次计算最大滚动距离: ${maxScroll.value}`);
    
    // 强制更新一次滚动位置，确保按钮状态正确
    scrollPosition.value = scrollContainer.value?.scrollLeft || 0;
    
    // 再次更新最大滚动距离，确保计算准确
    updateMaxScroll();
    console.log(`[ImageWall] 再次计算最大滚动距离: ${maxScroll.value}`);
    
    loading.value = false;
  };

  // 组件挂载后初始化
  onMounted(async () => {
    console.log('[ImageWall] 组件挂载开始');
    // 先进行初始化
    updateMaxScroll();
    console.log(`[ImageWall] 初始化时的最大滚动距离: ${maxScroll.value}`);
    
    // 等待图片加载完成
    await updateScrollAfterImagesLoad();
    
    // 确保滚动位置和最大滚动值已正确计算
    // 增加延迟时间，确保DOM完全渲染并计算准确
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 强制重新计算滚动值
    if (scrollContainer.value) {
      // 强制触发布局重新计算
      scrollContainer.value.offsetWidth;
      
      // 先设置滚动位置
      scrollPosition.value = scrollContainer.value.scrollLeft || 0;
      // 再次更新最大滚动距离
      updateMaxScroll();
      console.log(`[ImageWall] 最终计算的最大滚动距离: ${maxScroll.value}`);
      
      // 确保按钮状态正确
      if (maxScroll.value > 0) {
        // 如果有可滚动空间，确保右侧按钮启用
        scrollPosition.value = Math.min(scrollPosition.value, maxScroll.value);
        console.log(`[ImageWall] 有可滚动空间，右侧按钮应该启用`);
      } else {
        // 如果maxScroll仍然为0但实际上有多个图片，可能是计算错误，强制设置为正值
        const images = scrollContainer.value.querySelectorAll('img');
        if (images.length > 1) {
          console.log(`[ImageWall] 检测到${images.length}张图片但maxScroll为0，强制启用右侧按钮`);
          maxScroll.value = 1; // 强制设置为正值以启用右侧按钮
        }
      }
    }
    
    // 添加事件监听
    window.addEventListener('resize', () => {
      updateMaxScroll();
      // 在窗口大小变化时也更新滚动位置
      if (scrollContainer.value) {
        scrollPosition.value = scrollContainer.value.scrollLeft || 0;
      }
    });
    
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('scroll', handleScroll);
    }
    
    console.log('[ImageWall] 组件挂载完成');
  });
  </script>
  
  <style scoped>
  .image-wall-container {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  .image-wall-wrapper {
    flex: 1;
    overflow: hidden;
    position: relative;
  }
  
  .image-wall {
    display: flex;
    flex-wrap: nowrap;
    gap: 16px;
    padding: 16px 0;
  }
  
  .image-item {
    flex: 0 0 auto;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .image-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .scroll-button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: white;
    border: 1px solid #E0D9FC;
    cursor: pointer;
    z-index: 2;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .scroll-button:hover {
    background: #F8F6FE;
  }
  
  .scroll-button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  .left-button {
    margin-right: 8px;
  }
  
  .right-button {
    margin-left: 8px;
  }
  
  /* 适配移动端 */
  @media screen and (max-width: 768px) {
    .image-item {
      width: 150px;
      height: 120px;
    }
    
    .scroll-button {
      width: 32px;
      height: 32px;
    }
  }
  </style>